package com.douhulu.bytedance.common.util.http.apache;

import com.douhulu.bytedance.common.enums.ByteType;
import com.douhulu.bytedance.common.error.ByteErrorException;
import com.douhulu.bytedance.common.util.http.RequestHttp;
import com.douhulu.bytedance.common.util.http.SimpleGetRequestExecutor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;

import java.io.IOException;
import java.util.Map;

/**
 * <h2> 奕泽云 -  </h2>
 *
 * @Author: 奕泽云 - 曾庆雷
 * @Email: 75881401@qq.com
 * @Since: 2022-05-01 16:24
 * CopyRight：山西威斯汀文化传播有限公司
 */
@Slf4j
public class ApacheSimpleGetRequestExecutor extends SimpleGetRequestExecutor<CloseableHttpClient, HttpHost> {

    public ApacheSimpleGetRequestExecutor(RequestHttp requestHttp) {
        super(requestHttp);
    }

    @Override
    public String execute(String uri, Map<String, String> headers, String queryParam, ByteType byteType) throws ByteErrorException, IOException {
        if (queryParam != null) {
            if (uri.indexOf('?') == -1) {
                uri += '?';
            }
            uri += uri.endsWith("?") ? queryParam : '&' + queryParam;
        }

        HttpGet httpGet = new HttpGet(uri);
        if( headers != null ) {
            headers.keySet().forEach(key-> httpGet.addHeader(key, headers.get(key)));
        }
        if (requestHttp.getRequestHttpProxy() != null) {
            RequestConfig config = RequestConfig.custom().setProxy(requestHttp.getRequestHttpProxy()).build();
            httpGet.setConfig(config);
        }

        try (CloseableHttpResponse response = requestHttp.getRequestHttpClient().execute(httpGet)) {
            String responseContent = Utf8ResponseHandler.INSTANCE.handleResponse(response);
            return handleResponse(byteType, responseContent);
        } finally {
            httpGet.releaseConnection();
        }
    }

}
